import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import styles from './LoginPage.module.css';
import logo from '../../assets/images/login/logo.png';
import { UserOutlined, LockOutlined, EyeOutlined, EyeInvisibleOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import { _apiCaptcha, _apiLogin } from '../../api/index';
import Notification, { showNotification } from '../../components/message/message';

function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [rememberPassword, setRememberPassword] = useState(false);
  const [captcha, setCaptcha] = useState('');
  const [captchaImage, setCaptchaImage] = useState({ data: '', key: '' }); // 存储验证码图片URL和key
  const navigate = useNavigate();
  const location = useLocation();

  // 获取验证码的函数
  const refreshCaptcha = async () => {
    try {
      const response = await _apiCaptcha();
      
      if (response && response.data) {
        setCaptchaImage({
          data: response.data,
          key: response.key  // 保存验证码的 key
        });
      }
    } catch (error) {
      console.error('获取验证码失败:', error);
    }
  };

  // 组件加载时生成第一个验证码
  useEffect(() => {
    refreshCaptcha();
  }, []);

  // 检查是否已登录
  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      // 如果已登录，跳转到之前的页面或默认页面
      const from = location.state?.from?.pathname || '/admin/dashboard';
      navigate(from, { replace: true });
    }
  }, [navigate, location]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    
    // 表单验证
    if (!username.trim()) {
      showNotification('请输入登录账号', 'error');
      return;
    }
    
    if (!password.trim()) {
      showNotification('请输入登录密码', 'error');
      return;
    }

    if (!captcha.trim()) {
      showNotification('请输入验证码', 'error');
      return;
    }

    try {
      const loginParams = {
        userName: username,
        password: password,
        codeKey: captchaImage.key,
        codeValue: captcha
      };

      const response = await _apiLogin(loginParams);
      
      if (response.accessToken) {
        localStorage.setItem('token', response.accessToken);
        localStorage.setItem('refreshToken', response.refreshToken);
        showNotification('登录成功', 'success');
        setTimeout(() => {
          navigate('/admin/dashboard');
        }, 1500);
      } else {
        showNotification(response.message, 'error');
        refreshCaptcha();
      }
    } catch (error) {
      showNotification(error.response?.data?.message || '网络错误，请稍后重试', 'error');
      refreshCaptcha();
    }
  };

  return (
    <div className={styles.container}>
      <Notification />
      <img src={logo} alt="Logo" className={styles.logo} />
      <div className={styles.loginBox}>
        <h2 className={styles.title}>账号密码登录</h2>
        <form className={styles.form} onSubmit={handleSubmit}>
          <div className={styles.inputGroup}>
            <UserOutlined className={styles.icon} />
            <input
              type="text"
              className={styles.input}
              placeholder="请输入登录账号"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
          </div>
          <div className={styles.inputGroup}>
            <LockOutlined className={styles.icon} />
            <input
              type={showPassword ? "text" : "password"}
              className={styles.input}
              placeholder="请输入登录密码"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <span 
              className={styles.passwordIcon}
              onClick={() => setShowPassword(!showPassword)}
            >
              {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            </span>
          </div>
          <div className={styles.inputGroup}>
            <SafetyCertificateOutlined className={styles.icon} />
            <div className={styles.captchaContainer}>
              <input
                type="text"
                className={styles.captchaInput}
                placeholder="请输入验证码"
                value={captcha}
                onChange={(e) => setCaptcha(e.target.value)}
                maxLength={4}
              />
              <img
                src={captchaImage.data}
                alt="验证码"
                className={styles.captchaImage}
                onClick={refreshCaptcha}
              />
            </div>
          </div>
          <div className={styles.options}>
            <label className={styles.rememberPassword}>
              <input
                type="checkbox"
                checked={rememberPassword}
                onChange={(e) => setRememberPassword(e.target.checked)}
              />
              记住密码
            </label>
            <span className={styles.forgotPassword}>密码修改</span>
          </div>
          <button type="submit" className={styles.button}>登录</button>
        </form>
      </div>
    </div>
  );
}

export default LoginPage;